//
//  NSString+Regex.swift
//  测试-03-来源
//
//  Created by 刘凡 on 15/10/31.
//  Copyright © 2015年 joyios. All rights reserved.
//

import Foundation

extension String {
    
    /// 提取字符串中的链接&文字
    ///
    /// - returns: (链接 文字) 元组
    func href() -> (link: String, text: String)? {
        
        let pattern = "<a href=\"(.*?)\".*?>(.*?)</a>"
        let regex = try! NSRegularExpression(pattern: pattern, options: [])
        
        guard let result = regex.firstMatchInString(self,
                                                    options: [],
                                                    range: NSRange(location: 0, length: self.characters.count)) else {
                                                        print("没有找到匹配内容")
                                                        return nil
        }
        
        let str = self as NSString
        
        let r1 = result.rangeAtIndex(1)
        let link = str.substringWithRange(r1)
        let r2 = result.rangeAtIndex(2)
        let text = str.substringWithRange(r2)
        
        return (link, text)
    }
}